<template>
    <div class="result-container">
      <!-- 成绩概览 -->
      <div class="result-summary">
        <el-card shadow="hover">
          <div class="summary-content">
            <div class="score-display">
              <div class="total-score">{{ result.totalScore }}<span>分</span></div>
              <div class="score-desc">您的最终成绩</div>
            </div>
            <div class="summary-details">
              <div class="detail-item">
                <div class="detail-label">试卷名称</div>
                <div class="detail-value">{{ examInfo.name }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">考试时长</div>
                <div class="detail-value">{{ examInfo.timeLimit }}分钟</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">实际用时</div>
                <div class="detail-value">{{ formatTimeUsed(result.timeUsed) }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">提交时间</div>
                <div class="detail-value">{{ formatDateTime(result.submitTime) }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">正确率</div>
                <div class="detail-value">{{ calculateCorrectRate() }}%</div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
  
      <!-- 成绩分布 -->
      <div class="result-stats">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card shadow="hover">
              <div class="stat-item correct">
                <div class="stat-count">{{ result.correctCount || 0 }}</div>
                <div class="stat-label">答对题数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover">
              <div class="stat-item wrong">
                <div class="stat-count">{{ result.wrongCount || 0 }}</div>
                <div class="stat-label">答错题数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover">
              <div class="stat-item unanswered">
                <div class="stat-count">{{ result.unansweredCount || 0 }}</div>
                <div class="stat-label">未答题数</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
  
      <!-- 题目回顾 -->
      <div class="question-review">
        <el-card shadow="hover">
          <div slot="header" class="review-header">
            <span>题目回顾</span>
            <el-button  type="text"  @click="toggleShowAll">{{ showAll ? '只显示错题' : '显示全部题目' }}</el-button>
          </div>
          <div v-for="(item, index) in filteredQuestions" :key="item.question.id" class="review-item"
            :class="{
              'correct': item.user_answer.is_correct,
              'wrong': !item.user_answer.is_correct && item.user_answer.answer,
              'unanswered': !item.user_answer.answer
            }">
            <div class="question-header">
              <span class="question-index">第{{ index + 1 }}题</span>
              <span class="question-type">{{ getQuestionTypeText(item.question.type) }}</span>
              <span class="question-score">{{ item.question.score }}分</span>
              <el-tag :type="item.user_answer.is_correct ? 'success' : item.user_answer.answer ? 'danger' : 'info'" size="mini">
                {{ getAnswerStatusText(item.user_answer) }}
              </el-tag>
              <span class="user-score" v-if="item.user_answer.score !== null">得分: {{ item.user_answer.score }}分</span>
            </div>
            <div class="question-content">
              <div v-html="item.question.content" class="question-text"></div>
            </div>
  
            <!-- 选项展示 -->
            <div class="question-options" v-if="item.question.type !== 'judgment'">
              <div v-for="option in item.question.options" :key="option.id" class="option-item"
                :class="{
                  'correct-option': option.is_correct,
                  'user-selected': isOptionSelected(option.id, item.user_answer.answer),
                  'wrong-selected': isWrongSelected(option.id, item.user_answer.answer, option.is_correct)
                }">
                <span class="option-prefix">{{ getOptionPrefix(option.sequence) }}</span>
                <span class="option-text" v-html="option.text"></span>
                <span class="option-status">
                  <i class="el-icon-check" v-if="option.is_correct"></i>
                  <i class="el-icon-close" v-if="isWrongSelected(option.id, item.user_answer.answer, option.is_correct)"></i>
                </span>
              </div>
            </div>
  
            <!-- 判断题选项 -->
            <div class="question-options" v-if="item.question.type === 'judgment'">
              <div class="judgment-options">
                <div class="judgment-option"
                  :class="{
                    'correct-option': item.question.correct_answer === 'true',
                    'user-selected': item.user_answer.answer === 'true',
                    'wrong-selected': item.user_answer.answer === 'true' && !item.user_answer.is_correct
                  }">
                  <span>正确</span>
                  <span class="option-status">
                    <i class="el-icon-check" v-if="item.question.correct_answer === 'true'"></i>
                    <i class="el-icon-close" v-if="item.user_answer.answer === 'true' && !item.user_answer.is_correct"></i>
                  </span>
                </div>
                <div class="judgment-option"
                  :class="{
                    'correct-option': item.question.correct_answer === 'false',
                    'user-selected': item.user_answer.answer === 'false',
                    'wrong-selected': item.user_answer.answer === 'false' && !item.user_answer.is_correct
                  }">
                  <span>错误</span>
                  <span class="option-status">
                    <i class="el-icon-check" v-if="item.question.correct_answer === 'false'"></i>
                    <i class="el-icon-close" v-if="item.user_answer.answer === 'false' && !item.user_answer.is_correct"></i>
                  </span>
                </div>
              </div>
            </div>
  
            <!-- 答案解析 -->
            <div class="question-analysis" v-if="item.question.analysis">
              <div class="analysis-title">答案解析：</div>
              <div class="analysis-content" v-html="item.question.analysis"></div>
            </div>
  
            <!-- 评语 -->
            <div class="question-comment" v-if="item.user_answer.review_comment">
              <div class="comment-title">老师评语：</div>
              <div class="comment-content">{{ item.user_answer.review_comment }}</div>
            </div>
          </div>
        </el-card>
      </div>
  
      <!-- 底部操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="goToExamList">返回考试列表</el-button>
        <el-button @click="exportResult" v-if="!isMobile">导出成绩单</el-button>
        <el-button @click="printResult" v-if="!isMobile">打印成绩单</el-button>
      </div>
    </div>
  </template>
  
  <script>
  import { getExamRecordDetail, getExamDetail } from '@/api/study-ask'
  import { formatDateTime } from '@/utils/date'
  
  export default {
    name: 'ExamResult',
    data() {
      return {
        recordId: null,
        result: {
          total_score: 0,
          time_used: 0,
          submit_time: '',
          correct_count: 0,
          wrong_count: 0,
          unanswered_count: 0
        },
        examInfo: {
          name: '',
          time_limit: 0
        },
        questions: [],
        showAll: false,
        isMobile: false
      }
    },
    computed: {
      filteredQuestions() {
        return this.showAll 
          ? this.questions 
          : this.questions.filter(q => !q.user_answer.is_correct || !q.user_answer.answer)
      }
    },
    created() {
      this.recordId = this.$route.params.id
      this.checkMobile()
      this.loadResultData()
    },
    methods: {
      checkMobile() {
        this.isMobile = window.innerWidth < 768
      },
      async loadResultData() {
        try {
          // 获取考试记录详情
          const recordRes = await getExamRecordDetail(this.recordId)
          console.log(recordRes);
          this.result = recordRes.data
          
          // 获取考试信息
          const examRes = await getExamDetail(recordRes.data.examId)
          this.examInfo = examRes.data
          console.log(recordRes.data.questions)
          // 处理题目数据
          this.questions = recordRes.data.questions.map(item => {
            console.log(item.question)
            console.log(item.user_answer.answer);
            return {
              question: item.question,
              user_answer: {
                ...item.user_answer,
                answer: item.user_answer.answer ? JSON.parse(item.user_answer.answer) : null
              }
            }
          })
          
          // 统计答题情况
          this.calculateStats()
          
        } catch (error) {
          console.info(error)
          this.$message.error('加载考试结果失败: ' + error.message)
        }
      },
      calculateStats() {
        this.result.correct_count = this.questions.filter(q => q.user_answer.is_correct).length
        this.result.wrong_count = this.questions.filter(q => !q.user_answer.is_correct && q.user_answer.answer).length
        this.result.unanswered_count = this.questions.filter(q => !q.user_answer.answer).length
      },
      calculateCorrectRate() {
        const total = this.questions.length
        const correct = this.result.correct_count
        return total > 0 ? Math.round((correct / total) * 100) : 0
      },
      formatTimeUsed(seconds) {
        const mins = Math.floor(seconds / 60)
        const secs = seconds % 60
        return `${mins}分${secs}秒`
      },
      formatDateTime,
      getQuestionTypeText(type) {
        const types = {
          single: '单选题',
          multiple: '多选题',
          judgment: '判断题'
        }
        return types[type] || type
      },
      getAnswerStatusText(answer) {
        console.info("getAnswerStatusText");
        console.info(answer);
        if (!answer.answer) {
          return '未作答'
        }
        return answer.is_correct ? '回答正确' : '回答错误'
      },
      getOptionPrefix(sequence) {
        return String.fromCharCode(65 + sequence) + '. '
      },
      isOptionSelected(optionId, userAnswer) {
        if (!userAnswer) return false
        return Array.isArray(userAnswer) 
          ? userAnswer.includes(optionId)
          : userAnswer === optionId
      },
      isWrongSelected(optionId, userAnswer, isCorrect) {
        if (!userAnswer || isCorrect) return false
        return this.isOptionSelected(optionId, userAnswer)
      },
      toggleShowAll() {
        this.showAll = !this.showAll
      },
      goToExamList() {
        this.$router.push(`/study/ask/list`)
      },
      exportResult() {
        // 导出成绩单实现
        this.$message.info('导出功能开发中')
      },
      printResult() {
        window.print()
      }
    }
  }
  </script>
  <style scoped>
  .result-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  /* 成绩概览 */
  .result-summary {
    margin-bottom: 20px;
  }
  
  .summary-content {
    display: flex;
    align-items: center;
  }
  
  .score-display {
    text-align: center;
    padding: 0 40px;
  }
  
  .total-score {
    font-size: 48px;
    font-weight: bold;
    color: #409EFF;
    line-height: 1;
  }
  
  .total-score span {
    font-size: 16px;
    font-weight: normal;
  }
  
  .score-desc {
    font-size: 14px;
    color: #909399;
    margin-top: 5px;
  }
  
  .summary-details {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 15px;
  }
  
  .detail-item {
    display: flex;
  }
  
  .detail-label {
    color: #909399;
    margin-right: 10px;
    min-width: 60px;
  }
  
  .detail-value {
    color: #606266;
    font-weight: 500;
  }
  
  /* 成绩分布 */
  .result-stats {
    margin-bottom: 20px;
  }
  
  .stat-item {
    text-align: center;
    padding: 20px 0;
  }
  
  .stat-count {
    font-size: 32px;
    font-weight: bold;
    margin-bottom: 5px;
  }
  
  .stat-label {
    font-size: 14px;
    color: #909399;
  }
  
  .correct .stat-count {
    color: #67C23A;
  }
  
  .wrong .stat-count {
    color: #F56C6C;
  }
  
  .unanswered .stat-count {
    color: #909399;
  }
  
  /* 题目回顾 */
  .review-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .review-item {
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
    border-left: 4px solid #DCDFE6;
  }
  
  .review-item.correct {
    background-color: #f0f9eb;
    border-left-color: #67C23A;
  }
  
  .review-item.wrong {
    background-color: #fef0f0;
    border-left-color: #F56C6C;
  }
  
  .review-item.unanswered {
    background-color: #f4f4f5;
    border-left-color: #909399;
  }
  
  .question-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    flex-wrap: wrap;
  }
  
  .question-index {
    font-weight: bold;
    margin-right: 15px;
  }
  
  .question-type {
    font-size: 12px;
    color: #fff;
    background: #409EFF;
    padding: 2px 8px;
    border-radius: 4px;
    margin-right: 15px;
  }
  
  .question-score {
    color: #E6A23C;
    font-weight: bold;
    margin-right: 15px;
  }
  
  .user-score {
    margin-left: auto;
    color: #606266;
  }
  
  .question-text {
    line-height: 1.6;
  }
  
  .question-options {
    margin: 15px 0;
  }
  
  .option-item {
    padding: 10px 15px;
    margin: 8px 0;
    border-radius: 4px;
    background: #f5f7fa;
    display: flex;
    align-items: center;
  }
  
  .option-prefix {
    font-weight: bold;
    margin-right: 8px;
  }
  
  .option-text {
    flex: 1;
  }
  
  .option-status {
    margin-left: 10px;
    color: #67C23A;
  }
  
  .correct-option {
    background-color: #f0f9eb;
    border: 1px solid #e1f3d8;
  }
  
  .user-selected {
    background-color: #fdf6ec;
    border: 1px solid #faecd8;
  }
  
  .wrong-selected .option-status {
    color: #F56C6C;
  }
  
  .judgment-options {
    display: flex;
  }
  
  .judgment-option {
    padding: 10px 20px;
    margin-right: 20px;
    border-radius: 4px;
    background: #f5f7fa;
  }
  
  .question-analysis {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px dashed #DCDFE6;
  }
  
  .analysis-title {
    font-weight: bold;
    margin-bottom: 8px;
    color: #606266;
  }
  
  .analysis-content {
    line-height: 1.6;
    color: #606266;
  }
  
  .question-comment {
    margin-top: 15px;
    padding: 10px;
    background: #f4f4f5;
    border-radius: 4px;
  }
  
  .comment-title {
    font-weight: bold;
    margin-bottom: 5px;
  }
  
  .action-buttons {
    text-align: center;
    margin-top: 30px;
  }
  
  @media print {
    .action-buttons {
      display: none;
    }
  }
  
  @media (max-width: 768px) {
    .summary-content {
      flex-direction: column;
    }
    
    .score-display {
      margin-bottom: 20px;
    }
    
    .summary-details {
      grid-template-columns: 1fr;
    }
  }
  </style>